package com.k2.whereareyou;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import com.k2.whereareyou.engine.Engine;
import com.k2.whereareyou.interfaces.IConstants;
import com.k2.whereareyou.web.RequestController;
import com.k2.whereareyou.xml.PhotoXML;

public class PhotoDownloadActivity extends Activity implements IConstants, View.OnClickListener, OnCheckedChangeListener{
	
	private Button[] buttons;
	private TextView[] textViews;
	private EditText[] editTexts;
	private ImageButton[] imageButtons;
	private CheckBox checkBox;
	private byte language;
	private String path;
	private boolean save;
	private PhotoXML photoXML;
	boolean type;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        language = Engine.setLanguage(getApplicationContext());
        initLayout();
		initUI();
		path = getIntent().getExtras().getString("path");
//			path = Environment.getExternalStorageDirectory() + 
//					"/Where_are_you/cache/4.jpg";
		type = getIntent().getExtras().getBoolean("type");
		loadPhotoVideo();
		setDateCoordinates();
    }
	
	private void setDateCoordinates() {
		textViews[3].setText(new SimpleDateFormat("dd.mm.yyyy HH:mm").format(new Date()));
				
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
		String locationProvider = LocationManager.NETWORK_PROVIDER;
		Location l = locationManager.getLastKnownLocation(locationProvider);
	    
	    if (l != null) {
	    	textViews[1].setText("Latitude " + l.getLatitude() + 
					"  Longitude " + l.getLongitude());
	    }
	    else {
			textViews[1].setText("Country"); //TODO
		}
	}

	private void loadPhotoVideo() {
		try{
			if (type){
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 2;
				final Bitmap bitmap = BitmapFactory.decodeFile(path, null);
				ImageView foto = (ImageView) findViewById(R.id.imageView_foto);
				foto.setImageBitmap(bitmap);
				Log.d("startTypephoto", "1234");
			}
			else{
				VideoView video = (VideoView) findViewById(R.id.videoView_video);
				video.setVideoPath(path);
				video.setMediaController(new MediaController(this));
				video.requestFocus(0);
				video.start(); 
			}
		} catch (Exception e1) {
	        Intent error = new Intent(this, MainMenuActivity.class);
	        error.putExtra("error", true);
	        startActivity(error);
	        System.exit(0);
	    }catch (OutOfMemoryError e){
			Log.e("LOADING_RESOURCES_IMAGE_VIEW", "OUT OF MEMORY!!!");
		}
	}

	private void initUI(){
        
    	buttons = new Button[BUTTONS_NUMBER_PHOTO_DOWNLOAD.length];
    	for (int i=0; i < BUTTONS_NUMBER_PHOTO_DOWNLOAD.length; i++){
    		buttons[i] = (Button) findViewById(BUTTONS_NUMBER_PHOTO_DOWNLOAD[i]);
    		buttons[i].setText(TEXT_PHOTO_DOWNLOAD[language][6+i]);
    		buttons[i].setOnClickListener(this);
    	}
    	
    	imageButtons = new ImageButton[IMAGE_BUTTONS_NUMBER_PHOTO_DOWNLOAD.length];
    	for (int i=0; i < IMAGE_BUTTONS_NUMBER_PHOTO_DOWNLOAD.length; i++){
    		imageButtons[i] = (ImageButton) findViewById(IMAGE_BUTTONS_NUMBER_PHOTO_DOWNLOAD[i]);
    		imageButtons[i].setOnClickListener(this);
    	}
    	
    	textViews = new TextView[TEXTVIEWS_NUMBER_PHOTO_DOWNLOAD.length];
    	for (int i=0; i < TEXTVIEWS_NUMBER_PHOTO_DOWNLOAD.length; i++){
    		textViews[i] = (TextView) findViewById(TEXTVIEWS_NUMBER_PHOTO_DOWNLOAD[i]);
    		textViews[i].setText(TEXT_PHOTO_DOWNLOAD[language][i]);
    	}
    	
    	editTexts = new EditText[EDITTEXTS_NUMBER_PHOTO_DOWNLOAD.length];
    	for (int i=0; i < EDITTEXTS_NUMBER_PHOTO_DOWNLOAD.length; i++){
    		editTexts[i] = (EditText) findViewById(EDITTEXTS_NUMBER_PHOTO_DOWNLOAD[i]);
    	}

    	checkBox = (CheckBox) findViewById(R.id.checkBox_save_foto);
    	checkBox.setOnCheckedChangeListener(this);
    	checkBox.setText(TEXT_PHOTO_DOWNLOAD[language][5]);
    	
    	
	}
	
	private void initLayout() {
		setContentView(R.layout.activity_photo_download);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(Menu.NONE, IDM_PREF_CHANGE, Menu.NONE, Engine.TEXT_MENU_SETTINGS[language][0]);
    	menu.add(Menu.NONE, IDM_PREF_EXIT, Menu.NONE, Engine.TEXT_MENU_SETTINGS[language][1]);
    	menu.add(Menu.NONE, IDM_PREF_CLOSE, Menu.NONE, Engine.TEXT_MENU_SETTINGS[language][2]);
        return (super.onCreateOptionsMenu(menu));
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case IDM_PREF_CHANGE:
            	startActivity(new Intent(this, ChangeInfoActivity.class));
    	    	System.exit(0);
                break;
            case IDM_PREF_EXIT:
            	SharedPreferences prefs = getSharedPreferences("PreferensLogin", 0);
            	SharedPreferences.Editor editor = prefs.edit();
            	editor.putString("pass", "");
            	editor.commit();
            	startActivity(new Intent(this, MainActivity.class));
    	    	System.exit(0);
                break;
            case IDM_PREF_CLOSE:
            	System.exit(0);
                break;
            default:
                return false;
        }
        return true;
    }
	
	private void delete(String path) {
		try {
        File file = new File(path); 
        if (file.exists()) { 
                String deleteCmd = "rm -r " + path; 
                Runtime runtime = Runtime.getRuntime();  
                runtime.exec(deleteCmd);
        }
		} catch (IOException e) {
        }
	}

	@Override
	public void onClick(View activity) {
		switch (activity.getId()) {
	    case R.id.button_upload_photo:
	    	if (!save){
				this.delete(path);
			}
	    	createPhotoXML();
	    	//TODO
	      break;
	    case R.id.button_reshoot:
	    	onBackPressed();
	     break;
	    case R.id.imageButton_rotate_left:
	    	if (type){
	    		rotatePhoto(-90);
	    		loadPhotoVideo();
	    	}
	    	else{
	    		Engine.toast(getApplicationContext(), TEXT_PHOTO_DOWNLOAD[language][9]);
	    	}
	     break;
	    case R.id.imageButton_rotate_right:
	    	if (type){
	    		rotatePhoto(90);
	    		loadPhotoVideo();
	    	}
	    	else{
	    		Engine.toast(getApplicationContext(), TEXT_PHOTO_DOWNLOAD[language][9]);
	    	}
	    default:
	      break;
	    }
	}
	
	private void rotatePhoto(int degree){
		FileOutputStream out;
		try {
			
		BitmapFactory.Options bfOptions = new BitmapFactory.Options();
		bfOptions.inPurgeable = true;
		Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(path),null, bfOptions);
			Log.e("LOADING_RESOURCES", "bitmap");
		if (bmp.getWidth()>1024){
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPurgeable = true;
			options.inSampleSize = 2;
			bmp = BitmapFactory.decodeStream(new FileInputStream(path),null, options);
		}
		Matrix matrix = new Matrix();
	    matrix.postRotate(degree);
	    Bitmap rotateBm = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), 
	              matrix, true);
			Log.e("LOADING_RESOURCES", "bitmap_rotate");
	    out = new FileOutputStream(path);
	    rotateBm.compress(Bitmap.CompressFormat.JPEG, 100, out);
		} catch (Exception e) {
			Log.e("LOADING_RESOURCES", "error");
			Engine.toast(getApplicationContext(), TEXT_MESSAGES[language][6]);
		}
		catch (OutOfMemoryError e){
			Log.e("LOADING_RESOURCES", "OUT OF MEMORY!!!");
			Engine.toast(getApplicationContext(), TEXT_MESSAGES[language][6]);
		}
	}
	
	private void createPhotoXML() {
		SharedPreferences prefs = getSharedPreferences("PreferensLogin", 0);
		TelephonyManager telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
		photoXML = new PhotoXML();
		photoXML.setData(new SimpleDateFormat("dd.MM.yyyy HH:mm").format(new Date()));
		photoXML.setEmail(prefs.getString("email", ""));
		photoXML.setId(telephonyManager.getDeviceId());
		photoXML.setKomment(editTexts[0].getText().toString());
		photoXML.setKoord(textViews[1].getText().toString());
		
		RequestController.getResponseByXmlPhoto("url", photoXML, path);
    	startActivity(new Intent(this, FrendsActivity.class));
    	System.exit(0);
	}

	@Override
	public void onCheckedChanged(CompoundButton check, boolean save) {
		if(save)
			this.save=save;
		else
			this.save=save;
		
	}
	
	@Override
	public void onBackPressed() {
		startActivity(new Intent(this, MainMenuActivity.class));
		delete(path);
		System.exit(0);
	}

}
